package com.easy.common.util;
//验证码(用于生成和验证图形验证码),验证码过期时间8分钟

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;

import java.util.Map;
import java.util.UUID;

public class CaptchaUtil {
    //使用ExpiryMap存储验证码，可以自动过期
    private static final ExpiryMap expiryMap=new ExpiryMap();
    private static final long EXPIRY_TIME=1000*60*8;
    // 获取验证码
    public static Map getCaptcha(){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = cn.hutool.captcha.CaptchaUtil.createLineCaptcha(200, 100,4,5);
        //图片
        String imgbase64=Base64.encode(lineCaptcha.getImageBytes());
        System.out.println(imgbase64);
        //验证码中的编号
        String code = lineCaptcha.getCode();
        System.out.println(code);
        //生成唯一key用于标识这个验证码
        String key=UUID.randomUUID().toString();
        //构建返回结果
        Map map=Map.of("key",key,"base","data:image/png;base64,"+imgbase64);
        expiryMap.put(key,code,EXPIRY_TIME);
        return map;
    }
    //测试方法
    public static void main(String[] args) {
        ExpiryMap expiryMap=new ExpiryMap();
        expiryMap.put("1",1);
        expiryMap.put("2",2,8000);
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(expiryMap.get("1"));
        System.out.println(expiryMap.get("2"));
    }
    // 验证验证码
    public static boolean checkCaptcha(String key,String code){
        //从ExpiryMap中获取存储的验证码
        String captchaCode= (String) expiryMap.get(key);
        //验证码验证(忽略大小写)
        return code.equalsIgnoreCase(captchaCode);
    }
}
